//
//  Location.m
//  GPSRecord
//
//  Created by TianWan on 2017/1/7.
//  Copyright © 2017年 天玩. All rights reserved.
//

#import "Location.h"
#import "BGTask.h"

@interface Location() <CLLocationManagerDelegate>
{
    CLLocationManager *_manager;
    NSInteger _time;
    NSInteger _lastUpdateTime; // 最后上报的时间戳
    BOOL _isCollect;
}
@property (strong, nonatomic)CLGeocoder *geocoder;
@property (strong , nonatomic) BGTask *bgTask; //后台任务
@end

@implementation Location

+ (Location *)shareLocation
{
    static Location *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[Location alloc] init];
    });
    return instance;
    
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _lastUpdateTime = 0;
        _time = 0;
        _bgTask = [BGTask shareBGTask];
        [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(log) userInfo:nil repeats:YES];
        _manager = [[CLLocationManager alloc] init];
        _manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
        _manager.allowsBackgroundLocationUpdates = YES;
        _manager.pausesLocationUpdatesAutomatically = NO;
        _manager.delegate = self;
        _manager.distanceFilter = kCLDistanceFilterNone; // 不移动也可以后台刷新回调
        self.geocoder = [[CLGeocoder alloc] init];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
    }
    return self;
}

//后台监听方法
-(void)applicationEnterBackground
{
    NSLog(@"come in background");
    [self startLocation];
    [_bgTask beginNewBackgroundTask];
}


- (void)log
{
    _time ++ ;
    if ([_delegate respondsToSelector:@selector(Location:liveTime:)]) {
        [_delegate Location:self liveTime:_time];
    }
}

-(void)startLocation
{
    _isCollect = YES;
    UIAlertView *alert;
    if([UIApplication sharedApplication].backgroundRefreshStatus == UIBackgroundRefreshStatusDenied) {
        alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"应用定位没有打开，需要在在设置/通用/后台应用刷新开启" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    } else if ([UIApplication sharedApplication].backgroundRefreshStatus == UIBackgroundRefreshStatusRestricted) {
        alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"设备不可以定位" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    } else {
        NSLog(@"开始定位");
        if ([[UIDevice currentDevice].systemVersion floatValue]>= 8.0) {
            [_manager requestAlwaysAuthorization];
        }
        [_manager startUpdatingLocation];
        [self.bgTask beginNewBackgroundTask];

    }
}

-(void)stopLocation
{
    NSLog(@"停止定位");
    [_manager stopUpdatingLocation];
}

- (void)switchOff
{
    _isCollect = NO;
    [_manager startUpdatingLocation];
}

#pragma mark --delegate
//定位回调里执行重启定位和关闭定位
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    if (_isCollect = NO) {
        return;
    }
    
    NSInteger currentTime = [[NSDate date] timeIntervalSince1970];
    
    if (_lastUpdateTime == 0) {
        _lastUpdateTime = currentTime;
    }else {
        if (currentTime - _lastUpdateTime < 10) { // 最短间隔为10S
            _lastUpdateTime = currentTime;
            return;
        }else {
            _lastUpdateTime = currentTime;
        }
    }
    
    CLLocation *location = [locations firstObject];
    if (location) {
        
        if ([_delegate respondsToSelector:@selector(Location:coordinate:)]) {
            [_delegate Location:self coordinate:location.coordinate];
            
        }
        
        [self performSelector:@selector(startLocation) withObject:nil afterDelay:20];
        [self performSelector:@selector(stopLocation) withObject:nil afterDelay:5];
        
    }
    
    
    
    //    [self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
    //        dispatch_async(dispatch_get_main_queue(), ^{
    //            CLPlacemark *placemark = [placemarks firstObject];
    //            if ([_delegate respondsToSelector:@selector(Location:placemark:)]) {
    //                [_delegate Location:self placemark:placemark];
    //            }
    //        });
    //    }];
}



- (void)locationManager: (CLLocationManager *)manager didFailWithError: (NSError *)error
{
     NSLog(@"locationManager error:%@",error);
    
    switch([error code]) {
    
        case kCLErrorNetwork: { // general, network-related error
        
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络错误" message:@"请检查网络连接" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
            break;
        case kCLErrorDenied: {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请开启后台服务" message:@"应用定位没有打开，需要在在设置/通用/后台应用刷新开启" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
            break;
        default:
            break;
    }
}


@end
